package com.hr.dao.impl;

import java.util.Calendar;
import java.util.Date;
import java.util.List;

import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.jdbc.core.BeanPropertyRowMapper;
import org.springframework.jdbc.core.JdbcTemplate;
import org.springframework.stereotype.Repository;

import com.hr.dao.KaoqinDao;
import com.hr.model.KaoqinModel;
@Repository
public class KaoqinDaoImpl implements KaoqinDao {
	@Autowired
	private JdbcTemplate jdbcTemplate;

	@Override
	public List<KaoqinModel> findAll() {
		String sql = "select * from kaoqin ";
		List<KaoqinModel> wageList = jdbcTemplate.query(sql,new BeanPropertyRowMapper<KaoqinModel>(KaoqinModel.class));
		return wageList;
	}

	@Override
	public List<KaoqinModel> findAll(String user_id) {
		String sql = "select * from kaoqin where user_id=?";
		List<KaoqinModel> wageList = jdbcTemplate.query(sql,new BeanPropertyRowMapper<KaoqinModel>(KaoqinModel.class),user_id);
		return wageList;
	}

	private boolean haveWork(String user_id,String date) {
		String sql = "select count(*) from kaoqin where user_id=? and dakadate= ?";
		
		int count = jdbcTemplate.queryForInt(sql,user_id,date);
		return (count>0?true:false);
	}
	
	@Override
	public boolean workOn(String userId) {
		Calendar c = Calendar.getInstance();
		String today = c.get(Calendar.YEAR)+"-"+(c.get(Calendar.MONTH)+1)+"-"+c.get(Calendar.DAY_OF_MONTH);
		if(haveWork(userId,today)){
			String sql = "update kaoqin set shangban=? where user_id=? and dakadate=?";
			jdbcTemplate.update(sql, new Date(),userId,today);
		}else{
			String sql = "insert into kaoqin (user_id,shangban,dakadate) values(?,?,?)";
			jdbcTemplate.update(sql, userId,new Date(),today);
		}
		return true;
	}

	@Override
	public boolean workOff(String userId) {
		Calendar c = Calendar.getInstance();
		String today = c.get(Calendar.YEAR)+"-"+(c.get(Calendar.MONTH)+1)+"-"+c.get(Calendar.DAY_OF_MONTH);
		if(haveWork(userId,today)){
			String sql = "update kaoqin set xiaban=? where user_id=? and dakadate=?";
			jdbcTemplate.update(sql, new Date(),userId,today);
		}else{
			String sql = "insert into kaoqin (user_id,xiaban,dakadate) values(?,?,?)";
			jdbcTemplate.update(sql, userId,new Date(),today);
		}
		return true;
	}

	@Override
	public boolean checkWorkOn(String user_id) {
		Calendar c = Calendar.getInstance();
		String today = c.get(Calendar.YEAR)+"-"+(c.get(Calendar.MONTH)+1)+"-"+c.get(Calendar.DAY_OF_MONTH);
		String sql = "select count(*) from kaoqin where user_id=? and dakadate= ? and shangban is not null";
		int count = jdbcTemplate.queryForInt(sql,user_id,today);
		return (count>0?true:false);
	}
}
